package com.buaa.daas.controller;

import com.buaa.daas.constant.SaveUserType;
import com.buaa.daas.entity.StuInfo;
import com.buaa.daas.service.LoginService;
import com.buaa.daas.service.StuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StuInfoService stuInfoService;

    @GetMapping("/login")
    public String loginPage(){
        return "login";
    }

    @GetMapping("/regist")
    public String registPage(){
        return "regist";
    }

    @PostMapping("/registnew")
    public String registPagePost(@RequestParam("stunum") String stunum,
                                 @RequestParam("stuname") String stuname,
                                 @RequestParam("password") String password,
                                 Model model){
        StuInfo stuInfo = new StuInfo();

        String stunumUpper = stunum.toUpperCase();
        stuInfo.setStuNum(stunumUpper);
        stuInfo.setStuName(stuname);
        stuInfo.setStuPsd(password);

        int saveResultType = stuInfoService.saveNewUser(stuInfo);
        if(saveResultType == SaveUserType.SaveUserTypeEnum.REGIST_SUCCESS.getCode()){
            //注册成功，跳转到登录界面
            return "login";
        }else if(saveResultType == SaveUserType.SaveUserTypeEnum.STUNUM_EXISTED.getCode()){
            //已经有存在的学号了，请不要重复注册
            model.addAttribute("registMsg",SaveUserType.SaveUserTypeEnum.STUNUM_EXISTED.getMsg());

            return "regist";
        }

        return "regist";
    }

    @PostMapping("/login/auth")
    public String login(@RequestParam("stunum") String stunum,
                        @RequestParam("password") String password,
                        HttpServletResponse response){
        //处理成大小，方便用户前端页面输入
        String stunumUpper = stunum.toUpperCase();

        boolean flag = loginService.checkLogin(stunumUpper, password);
        if(flag){
            //登录成功
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,stunum,3, TimeUnit.DAYS);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            cookie.setMaxAge(3*24*60*60);
            response.addCookie(cookie);

            return "index";
        }

        return "redirect:/login";
    }
}